//
//  AppDelegate.m
//  DAU-iOS
//
//  Created by XiangDongMBP on 16/11/12.
//  Copyright © 2016年 East. All rights reserved.
//

#import "AppDelegate.h"
#import <IQKeyboardManager.h>
#import <YYWebImage.h>
#import "DAUTabVC.h"

// 引入JPush功能所需头文件
#import "JPUSHService.h"
// iOS10注册APNs所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif

@interface AppDelegate ()<JPUSHRegisterDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    // 配置全局的界面属性
    [self setGlobalAppearance];
    // 全局配置键盘
    [self initKeyboard];
    // 设置图片缓存时长
    [self initYYWebImage];
    // 初始化模型
    self.domain = [[NSUserDefaults standardUserDefaults] objectForKey:DAU_USERDEF_SERVER_DOMAIN];
    self.dauModel = [[DAUModel alloc] init];
    // 极光推送
    [self initJPush:launchOptions];
    
    BOOL autoLogin = [[NSUserDefaults standardUserDefaults] boolForKey:DAU_USERDEF_AUTOLOGIN];
    if (autoLogin) {
        self.window.rootViewController = [[DAUTabVC alloc] init];
    }
    
    return YES;
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

#pragma mark - 系统推送相关
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    NSLog(@"收到推送了%@", userInfo);
    [self processJPush:userInfo];
    
    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    // Required,For systems with less than or equal to iOS6
    [JPUSHService handleRemoteNotification:userInfo];
}

#pragma mark- JPUSHRegisterDelegate
// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    NSLog(@"iOS10前台收到推送%@", userInfo);
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    NSLog(@"iOS10后台收到了推送%@", userInfo);
    [self processJPush:userInfo];
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler();  // 系统要求执行这个方法
}

#pragma mark - 全局页面属性设置
//全局设置导航栏的颜色，TabBar的颜色
- (void)setGlobalAppearance {
    //UINavigationBar
    [[UINavigationBar appearance] setBarTintColor:DAU_COLOR_NavBg(1.0)];
    [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
    NSDictionary *textAttributes = @{NSForegroundColorAttributeName: [UIColor whiteColor],
                                     NSFontAttributeName: [UIFont systemFontOfSize:18]};
    [[UINavigationBar appearance] setTitleTextAttributes:textAttributes];
    
    //UIBarButtonItem
    //    NSDictionary * barItemAttributes = @{NSForegroundColorAttributeName: [UIColor whiteColor],
    //                                         NSFontAttributeName: [UIFont systemFontOfSize:14]};
    NSDictionary * barItemAttributes = @{NSForegroundColorAttributeName: [UIColor whiteColor]};
    [[UIBarButtonItem appearance] setTitleTextAttributes:barItemAttributes forState:UIControlStateNormal];
    
    //TabBar
    [[UITabBar appearance] setTintColor:DAU_COLOR_NavBg(1.0)];
//    NSDictionary * itemAttributes = @{NSFontAttributeName: [UIFont systemFontOfSize:9]};
//    [[UIBarItem appearance] setTitleTextAttributes:itemAttributes forState:UIControlStateNormal];
}

- (void)initKeyboard {
    // 键盘
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
}

- (void)initYYWebImage {
    // 设置图片缓存时长
    YYImageCache *cache = [YYWebImageManager sharedManager].cache;
    cache.diskCache.ageLimit = 30 * 24 * 60 * 60;   // 30天
}

#pragma mark - 极光推送
- (void)initJPush:(NSDictionary *)launchOptions {
    //Required
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
        JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
        entity.types = UNAuthorizationOptionAlert|UNAuthorizationOptionBadge|UNAuthorizationOptionSound;
        [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    }
    else if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                          UIUserNotificationTypeSound |
                                                          UIUserNotificationTypeAlert)
                                              categories:nil];
    }
    else {
        //categories 必须为nil
//        [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
//                                                          UIRemoteNotificationTypeSound |
//                                                          UIRemoteNotificationTypeAlert)
//                                              categories:nil];
    }
    
    // Required
    // init Push
    // notice: 2.1.5版本的SDK新增的注册方法，改成可上报IDFA，如果没有使用IDFA直接传nil
    // 如需继续使用pushConfig.plist文件声明appKey等配置内容，请依旧使用[JPUSHService setupWithOption:launchOptions]方式初始化。
    [JPUSHService setupWithOption:launchOptions appKey:DAU_JPUSH_APPKEY
                          channel:@"App Store"
                 apsForProduction:YES
            advertisingIdentifier:nil];
    
    
    // 启动APP时，清空角标
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
        [[UNUserNotificationCenter currentNotificationCenter] getDeliveredNotificationsWithCompletionHandler:^(NSArray<UNNotification *> * _Nonnull notifications) {
            NSLog(@"当前通知栏上面的消息数量%zd, %@", notifications.count, notifications);
            // 本地手机端的数量
            [[UIApplication sharedApplication] setApplicationIconBadgeNumber:notifications.count];
            // 极光服务器的角标数量
            [JPUSHService setBadge:notifications.count];
        }];
    } else {
        // 本地手机端的数量
        [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
        // 极光服务器的角标数量
        [JPUSHService resetBadge];
    }
}

- (void)processJPush:(NSDictionary *)userInfo {
    NSLog(@"收到的推送消息%@", userInfo);
    
    // 把角标-1
    NSInteger count = [UIApplication sharedApplication].applicationIconBadgeNumber - 1;
    if (count >= 0) {
        // 本地手机端的数量
        [[UIApplication sharedApplication] setApplicationIconBadgeNumber:count];
        // 极光服务器的角标数量
        [JPUSHService setBadge:count];
    }
    
    // 处理消息
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:userInfo[@"content"] preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"确定", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self requestConfirmMsg:userInfo[@"id"] type:userInfo[@"type"]];
    }]];
    [self.window.rootViewController presentViewController:alert animated:YES completion:nil];
}

- (void)requestConfirmMsg:(NSString *)msgId type:(NSString *)type {
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.window.rootViewController.view animated:YES];
    
    NSString *urlStr = [DAUUrlProtocolMerger apiConfirmMsg];
    NSDictionary *pars = @{@"id"   : msgId,
                           @"type" : type};
    [XDAFHttpRequest GET:urlStr parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"登录成功返回%@", responseObject);
        [hud hideAnimated:YES];
        [MBProgressHUD showPromptWithAutoHideInView:self.window.rootViewController.view message:responseObject[@"msg"]];
//        if ([responseObject[@"errCode"] integerValue] == 200) {
//        } else {
//            [MBProgressHUD showPromptWithAutoHideInView:self.window.rootViewController.view message:responseObject[@"msg"]];
//        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"登录失败%@", error);
        [hud hideAnimated:NO];
        [MBProgressHUD showPromptWithAutoHideInView:self.window.rootViewController.view message:NSLocalizedString(@"网络请求失败", nil)];
    }];
}

@end
